define(['app', 'clipboard', 'ace-language-tools'], function(app, Clipboard) {
    app.controller('EditCodeController', function(xContext, $uibModalInstance, $timeout, toastr) {
        var self = this;

        var codeEditor = null;

        self.init = function() {
            var snippet = '';
            if (xContext.lang == 'curl') {
                var codeLines = [];
                // method
                codeLines.push('curl -X ' + xContext.params.method);
                // url
                codeLines.push(xContext.params.url);
                // headers
                if (_.size(xContext.params.headers) > 0) {
                    _.forEach(xContext.params.headers, function(value, name) {
                        codeLines.push("-H '" + name + ": " + value + "'");
                    });
                }
                // body
                if (xContext.params.body) {
                    switch (xContext.params.body.type) {
                        case 'form-data':
                            _.forEach(xContext.params.body.data, function(value, name) {
                                codeLines.push("-F '" + name + "=" + value + "'");
                            });
                            break;
                        case 'x-www-form-urlencoded':
                            var query = _.map(xContext.params.body.data, function(value, name) {
                                return name + '=' + value;
                            }).join('&');
                            codeLines.push("-d '" + encodeURI(query) + "'");
                            break;
                        case 'raw':
                            codeLines.push("-d '" + xContext.params.body.data + "'");
                            break;
                        case 'binary':
                        default: break;
                    }
                }
                snippet = codeLines.join(' \\\n  ');
            }

            // code editor
            codeEditor = ace.edit('code-editor');
            codeEditor.setOptions({
                mode: 'ace/mode/sh',
                fontSize: 13,
                wrap: true,
                showPrintMargin: false,
                autoScrollEditorIntoView: true,
                enableBasicAutocompletion: true,
                enableSnippets: true,
                enableLiveAutocompletion: true
            });

            $timeout(function() {
                codeEditor.setValue(snippet, -1);
                codeEditor.resize();
            });

            new Clipboard('#copy-code', {
                text: function() {
                    return codeEditor.getValue();
                }
            }).on('success', function(e) {
                toastr.success('已复制到剪贴板！');
            });
        }

        self.close = function() {
            $uibModalInstance.close(true);
        }
    });
});
